package com.iteaj.iot.server.endpoints;

import com.iteaj.iot.server.ServerComponentFactory;
import com.iteaj.iot.server.websocket.WebSocketServerListener;
import com.iteaj.iot.server.websocket.impl.DefaultWebSocketServerProtocol;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 应用服务详情信息
 */
public class ServerHealthWebsocketEndpoint implements WebSocketServerListener, ApplicationContextAware {

    private ApplicationContext applicationContext;
    private final ServerComponentFactory componentFactory;

    public ServerHealthWebsocketEndpoint(ServerComponentFactory componentFactory) {
        this.componentFactory = componentFactory;
    }

    @Override
    public String uri() {
        return "/iot/endpoint/health";
    }

    @Override
    public void onText(DefaultWebSocketServerProtocol protocol) {
        long startupDate = this.applicationContext.getStartupDate();
        String textBuild = ServerHealthBuilder.textBuild(startupDate, this.componentFactory);
        protocol.response(textBuild);
    }

    @Override
    public void onClose(DefaultWebSocketServerProtocol protocol) {

    }

    @Override
    public void onBinary(DefaultWebSocketServerProtocol protocol) {
        long startupDate = this.applicationContext.getStartupDate();
        byte[] bytes = ServerHealthBuilder.binaryBuild(startupDate, this.componentFactory);
        protocol.response(bytes);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
